package com.gopay.bis.service.bank.impl.ebank;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.TransUtils;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.BankOrderManager;
import com.gopay.bis.manager.bank.ebank.YsPayManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.YsPayConstants;
import com.gopay.common.constants.bank.YsPayOrderStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.yspay.ebank.YspayMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 银盛支付业务实现
 * 
 * YsPayBankServiceImpl.java
 * 
 * @author lilili
 */
public class YsPayBankServiceImpl implements BankInteractRemoteService {

    private static Logger logger = LoggerFactory.getLogger(YsPayBankServiceImpl.class);
    
    @Resource(name = "ysPayManager")
    YsPayManager ysPayManager;
    
    @Resource(name = "bankOrderManager")
    private BankOrderManager bankOrderManager;

    @Override
    public Result pay(BaseMessage base) {
        Result result = new Result(false);
        YspayMessage message = new YspayMessage();
        BeanUtils.copyProperties(base, message);
        try {
            message = (YspayMessage) ysPayManager.sign(message);
            result.setDefaultModel(message);
            result.setSuccess(true);
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6029);
        }
        return result;
    }

    @Override
    public Result bankBack(BaseMessage base) {
        Result result = new Result(false);
        YspayMessage message = new YspayMessage();
        BeanUtils.copyProperties(base, message);
        try {
            message = (YspayMessage) ysPayManager.verify(message);
            String amount = TransUtils.amountConvert2Yuan(message.getOrderAmount());
            BankOrder bankOrder = null;
            bankOrder = bankOrderManager.getBankOrderById(message.getBankOrderId());
            message.setOrderId(bankOrder.getOrderId());
            result.setModel("res", message);
            result.setDefaultModel(message.isVerify());
            result.setSuccess(true);
            if (result != null && result.isSuccess() && (Boolean) result.getDefaultModel()) {
                Map<String, String> param = new HashMap<String, String>();
                if (base.isFront()) {
                    // 如果该订单成功通知后台地址入账
                    param.put("orderId", message.getOrderId());
                    param.put("amt", amount);
                    param.put("cardType", "Unknown");
                    param.put("notifyNum", "1");
                    param.put("payStatus", "00");
                    param.put("retCode", "00");
                    param.put("retMsg", "");
                    param.put("signData", message.getSignMessage());
                    param.put("isFront", base.isFront() + "");
                    result.setModel("isNotifyCashier", param);
                    result.setOrderStatus(true);
                }
                else {
                    if (message.getBusiState() != null
                            && message.getBusiState().equals(YsPayConstants.TRAN_YSPAY_DEAL_SUCCESS)) {
                        // 如果该订单成功通知后台地址入账
                        param.put("orderId", message.getOrderId());
                        param.put("amt", amount);
                        param.put("cardType", "Unknown");
                        param.put("notifyNum", "1");
                        param.put("payStatus", "00");
                        param.put("retCode", "00");
                        param.put("retMsg", "");
                        param.put("signData", message.getSignMessage());
                        param.put("isFront", base.isFront() + "");
                        result.setModel("isNotifyCashier", param);
                        result.setOrderStatus(true);
                    } else {
                        // 通知后台地址该订单失败
                        param.put("orderId", message.getOrderId());
                        param.put("amt", amount);
                        param.put("cardType", "Unknown");
                        param.put("notifyNum", "1");
                        param.put("payStatus", "01");
                        param.put("retCode", "01");
                        param.put("retMsg", "");
                        param.put("signData", message.getSignMessage());
                        param.put("isFront", base.isFront() + "");
                        result.setModel("isNotifyCashier", param);
                        result.setOrderStatus(false);
                    }
                }
                
                logger.error("bankservice notify cashier param:"+param);
            }

        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
        }
        return result;
    }

    @Override
    public Result query(BaseMessage base) {
        Result result = new Result(false);
        YspayMessage message = new YspayMessage();
        BeanUtils.copyProperties(base, message);
        try {
            message = (YspayMessage) ysPayManager.query(message);
            result.setDefaultModel(message);
            result.setSuccess(true);
            if (BisPayCheckUtils.checkExternalOrderID(base.getOrderId())) {
                Map<String, String> param = new HashMap<String, String>();
                param.put("orderId", base.getOrderId());
                param.put("amount", base.getAmount().toString());
                if (message == null) {
                    // 查询订单为空
                    param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
                    param.put("returnMessage", "银行返回对账结果为空");
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    result.setModel("queryResult", param);
                    return result;
                }
                if (!StringUtils.equals(YsPayConstants.QUERY_YSPAY_RETURN_SUCCESS, message.getCode())) {
                    // 订单未成功支付
                    param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
                    param.put("returnMessage", message.getNote());
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    result.setModel("queryResult", param);
                    return result;
                }
                if (!StringUtils.equals(YsPayConstants.QUERY_YSPAY_DEAL_SUCCESS, message.getBusiState())) {
                    // 查询订单错误
                    param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
                    param.put("returnMessage", message.getNote());
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    result.setModel("queryResult", param);
                    return result;
                }
                if (message.getState() != null && !message.getState().equals("")) {
                    // 成功处理
                    if (StringUtils.equals(YsPayConstants.QUERY_YSPAY_STATE_SUCC, message.getState())) {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
                        param.put("returnMessage", "交易成功");
                    }
                    // 失败处理
                    else if (StringUtils.equals(YsPayConstants.QUERY_YSPAY_STATE_FAIL, message.getState())) {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
                        String errMsg = YsPayOrderStatus.getName(message.getState());
                        if (errMsg != null) {
                            param.put("returnMessage", errMsg);
                        } else {
                            param.put("returnMessage", "银行返回交易失败");
                        }
                    } else if (StringUtils.equals(YsPayConstants.QUERY_YSPAY_STATE_DEAL, message.getState())) {
                        // 银行订单状态为处理中
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                        String errMsg = YsPayOrderStatus.getName(message.getState());
                        if (errMsg != null) {
                            param.put("returnMessage", errMsg);
                        } else {
                            param.put("returnMessage", "银行返回交易处理中");
                        }
                    } else {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                        String errMsg = YsPayOrderStatus.getName(message.getState());
                        if (errMsg != null) {
                            param.put("returnMessage", errMsg);
                        } else {
                            param.put("returnMessage", "银行返回交易失败");
                        }
                    }
                }
                // 没有查到订单
                else {
                    param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    param.put("returnMessage", "银行返回订单未查到");
                }
                result.setModel("queryResult", param);
            }
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6033);
        }
        return result;
    }

    @Override
    public Result refund(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result dayend(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result queryBack(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refundBack(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refundQuery(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public Result sendBankRefund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

}
